package com.istock.union.user.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.stereotype.Repository;

import com.istock.base.task.model.QiluTask;
import com.istock.base.task.model.TaskExecContext;
import com.istock.base.task.model.TaskExecResult;
import com.istock.base.task.service.QiluTaskService;
import com.istock.union.user.service.UserOnlineInfoService;

@Repository("UserOnlineTask")
public class UserOnlineTask {

	@Autowired
	private UserOnlineInfoService userOnlineInfoService;
	@Autowired
	private QiluTaskService qiluTaskService;
	
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public void addClearOnlineExpireTask() {
		//真正控制执行周期的,是taskNo的生成
		CronSequenceGenerator generator = new CronSequenceGenerator("23 0/1 * * * ?" , TimeZone.getDefault());
		String taskNo = format.format(generator.next(new Date()));
		try {
			QiluTask task = qiluTaskService.addQiluTask("CLEAR_ONLINE", taskNo, "spring:UserOnlineTask.clearOnlineExpireHandler" , new HashMap<String , String>() , 1, 1, 1);
			qiluTaskService.asynExecuteTask(task);
		}catch(Exception e) {
			logger.error("",e);
			logger.error("taskType:[CLEAR_ONLINE] , taskNo:["+taskNo+"] has duplicat record , ignor this task executing");
		}
	}
	
	public TaskExecResult clearOnlineExpireHandler(TaskExecContext context) {
		logger.info("ready to execute user online expire clear task===============");
		int count = userOnlineInfoService.clearExpireToken();
		logger.info("end for execute user online expire clear task , delete {} record===============" , count);
		return new TaskExecResult(true);
	}
}
